﻿using System;
using System.Collections.Generic;

namespace UniRx.Operators
{
	// Token: 0x02000290 RID: 656
	internal class DistinctUntilChangedObservable<T, TKey> : OperatorObservableBase<T>
	{
		// Token: 0x06000E94 RID: 3732 RVA: 0x00044A34 File Offset: 0x00042E34
		public DistinctUntilChangedObservable(IObservable<T> source, Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer) : base(source.IsRequiredSubscribeOnCurrentThread<T>())
		{
			this.source = source;
			this.comparer = comparer;
			this.keySelector = keySelector;
		}

		// Token: 0x06000E95 RID: 3733 RVA: 0x00044A57 File Offset: 0x00042E57
		protected override IDisposable SubscribeCore(IObserver<T> observer, IDisposable cancel)
		{
			return this.source.Subscribe(new DistinctUntilChangedObservable<T, TKey>.DistinctUntilChanged(this, observer, cancel));
		}

		// Token: 0x04000875 RID: 2165
		private readonly IObservable<T> source;

		// Token: 0x04000876 RID: 2166
		private readonly IEqualityComparer<TKey> comparer;

		// Token: 0x04000877 RID: 2167
		private readonly Func<T, TKey> keySelector;

		// Token: 0x02000291 RID: 657
		private class DistinctUntilChanged : OperatorObserverBase<T, T>
		{
			// Token: 0x06000E96 RID: 3734 RVA: 0x00044A6C File Offset: 0x00042E6C
			public DistinctUntilChanged(DistinctUntilChangedObservable<T, TKey> parent, IObserver<T> observer, IDisposable cancel) : base(observer, cancel)
			{
				this.parent = parent;
			}

			// Token: 0x06000E97 RID: 3735 RVA: 0x00044AA0 File Offset: 0x00042EA0
			public override void OnNext(T value)
			{
				TKey x;
				try
				{
					x = this.parent.keySelector(value);
				}
				catch (Exception error)
				{
					try
					{
						this.observer.OnError(error);
					}
					finally
					{
						base.Dispose();
					}
					return;
				}
				bool flag = false;
				if (this.isFirst)
				{
					this.isFirst = false;
				}
				else
				{
					try
					{
						flag = this.parent.comparer.Equals(x, this.prevKey);
					}
					catch (Exception error2)
					{
						try
						{
							this.observer.OnError(error2);
						}
						finally
						{
							base.Dispose();
						}
						return;
					}
				}
				if (!flag)
				{
					this.prevKey = x;
					this.observer.OnNext(value);
				}
			}

			// Token: 0x06000E98 RID: 3736 RVA: 0x00044B8C File Offset: 0x00042F8C
			public override void OnError(Exception error)
			{
				try
				{
					this.observer.OnError(error);
				}
				finally
				{
					base.Dispose();
				}
			}

			// Token: 0x06000E99 RID: 3737 RVA: 0x00044BC4 File Offset: 0x00042FC4
			public override void OnCompleted()
			{
				try
				{
					this.observer.OnCompleted();
				}
				finally
				{
					base.Dispose();
				}
			}

			// Token: 0x04000878 RID: 2168
			private readonly DistinctUntilChangedObservable<T, TKey> parent;

			// Token: 0x04000879 RID: 2169
			private bool isFirst = true;

			// Token: 0x0400087A RID: 2170
			private TKey prevKey = default(TKey);
		}
	}
}
